package com.taobao.phoenix.qtdemo.biz;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
import com.taobao.phoenix.qtdemo.domain.AdTask;
import com.trolltech.qt.core.QUrl;
import com.trolltech.qt.webkit.QWebElement;
import com.trolltech.qt.webkit.QWebView;

public class BrowserController implements InitializingBean, DisposableBean {
	
	private static Logger LOG = LoggerFactory.getLogger("browser");

	private QWebView browser;
	
	private AdTask currentTask;
	
	@Override
	public void afterPropertiesSet() throws Exception {
		browser = new QWebView();
		browser.page().mainFrame().loadFinished.connect(this, "onPageLoadFinished(boolean)");
		browser.page().mainFrame().urlChanged.connect(this, "onUrlChanged(QUrl)");
		browser.show();
		LOG.info("initilize BrowserController success");
	}
	
	@Override
	public void destroy() throws Exception {
		if(browser!=null)
			browser.close();
	}
	
		
	public void onUrlChanged(QUrl url) {
		LOG.info("url changed to----, url="+url.toString());
	}
	
	public void onPageLoadFinished(boolean ok) {
		if(!ok) {
			String url = browser.url().toString();
			LOG.error("page load failed----, url="+url);
			return;
		}
		
		String url = browser.url().toString();
		LOG.info("page load finished----, url="+url);
			
		
		if(url.startsWith("https://login.taobao.com")) {
			if(currentTask==null)
				return;
			
			
			String userName = currentTask.getWorkerNick();
			String pwd = currentTask.getWorkerPwd();
			
			QWebElement docElem = browser.page().mainFrame().documentElement();	
			// input username
			QWebElement nameInputElem = docElem.findFirst("#TPL_username_1");
			nameInputElem.setFocus();
			nameInputElem.setAttribute("value", userName);
			
			// input pwd
			QWebElement pwdInputElem = docElem.findFirst("#TPL_password_1");
			if(pwdInputElem==null) {
				pwdInputElem = docElem.findFirst("#Password_Edit_IE");
			}
			pwdInputElem.setFocus();
			pwdInputElem.setAttribute("value", pwd);
		
			// click login button
			QWebElement submitBtn = docElem.findFirst("#J_SubmitStatic");
			submitBtn.evaluateJavaScript("this.click()");
		} else if(url.startsWith("http://i.taobao.com")) {
			if(currentTask==null)
				return;
			
			gotoTalkPage(currentTask.getTargetUserNick());
		} else if(url.indexOf("logout.jhtml")>0) {
			LOG.debug("logout success. then go to login page");
			gotoLoginPage();
		}
	}
	
	
	public void gotoLoginPage() {
		browser.load(new QUrl("http://login.taobao.com"));
	}
	
	public void gotoLogoutPage() {
		browser.load(new QUrl("http://login.taobao.com/member/logout.jhtml"));
	}
	
	public void gotoTalkPage(String targetNick) {
		String encodedNick = null;
//		try {
//			encodedNick = URLEncoder.encode(targetNick, "UTF-8");
//		} catch (UnsupportedEncodingException e) {
//			LOG.error("encode nick error", e);
//		}
		encodedNick = targetNick;
		browser.load(new QUrl("http://www.taobao.com/webww/ww.php?ver=3&touid="+encodedNick+"&siteid=cntaobao&status=1&charset=utf-8"));
	}
	
	
	public AdTask getCurrentTask() {
		return currentTask;
	}

	public void setCurrentTask(AdTask currentTask) {
		this.currentTask = currentTask;
	}
	
	public QWebView getBrowser() {
		return browser;
	}

	public void setBrowser(QWebView browser) {
		this.browser = browser;
	}

	

//	public static void main(String args[]) {
//		QApplication.initialize(args);
//		BrowserController controller = new BrowserController();
//		demo.run();
//		QApplication.exec();		
//	}
}
